// app/model/product_category_model.js
'use strict';

module.exports = app => {
  const { STRING, INTEGER, DATE } = app.Sequelize;

  const ProductCategory = app.model.define('product_category', {
    id: {
      type: INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    name: {
      type: STRING(100),
      allowNull: false,
      comment: '类目名称'
    },
    parentId: {
      type: INTEGER,
      allowNull: true,
      field: 'parent_id',
      comment: '父类目ID，顶级类目为null'
    },
    level: {
      type: INTEGER,
      allowNull: false,
      defaultValue: 1,
      comment: '类目层级：1-一级类目，2-二级类目，3-三级类目，4-四级类目'
    },
    sort: {
      type: INTEGER,
      defaultValue: 0,
      comment: '排序值，越小越靠前'
    },
    status: {
      type: STRING(20),
      defaultValue: 'active',
      comment: '类目状态: active-启用, inactive-禁用'
    },
    createdAt: {
      type: DATE,
      field: 'created_at'
    },
    updatedAt: {
      type: DATE,
      field: 'updated_at'
    }
  }, {
    tableName: 'product_categories',
    timestamps: true,
    underscored: true // 使用下划线命名
  });

  // 定义与产品的关联关系
  ProductCategory.associate = function() {
    // 确保关联的模型存在
    if (app.model.Product) {
      ProductCategory.hasMany(app.model.ProductModel, {
        foreignKey: 'category_id',
        as: 'products'
      });
    }
  };

  return ProductCategory;
};